var http = require('http')
var https = require('https')
var errorLogger = require("pomelo-logger").getLogger("error-log");
var WXBizDataCrypt = require('./WXBizDataCrypt')
module.exports = {}
var access_token = ""
var jsapi_ticket = ""
var appid = "wxc1f0bda723943c7e"
var appidList = {
  "wxf641fc23bb1aca37" : "d19bacb6dace7de5c749b900082e25b2",
  "wx5b4f3b57b90be14b" : "67fc1bd9ca819ae433fb865539e79120",
  "wx2db56a4e53213071" : "7dfcaf7ca53af47eec33dfe7e1ac06e9",
  "wxeaa2aecc689920cf" : "e48cda084c95b608fee4d9456b094c16",
  "wxc066905ada5ea6d8" : "5f27b274fee87a6bc4e6757cab9abf9b",
  "wxbf5f63122440c968" : "a15c49a091c976ddd2c28f1021bafd42",
  "wxc1f0bda723943c7e" : "dedbacdc18615efc0d5f0ebb666117b8"
}
var timer = false
var local = {}
var session_keyMap = {}
module.exports.H5GetData = function(code,count,cb) {
    var string = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+appid
    +"&secret="+appidList[appid]+"&code="+code+"&grant_type=authorization_code"
    // var string = "http://pay.5d8d.com/H5Index/getAccessToken?code="+code
    var req=https.get(string,function(res){
        var data = data
        res.on("data",function(chunk) {
          data += chunk
        })
        res.on("end",function() {
          data = data.replace("undefined","")
          data = JSON.parse(data)
          cb(data)
        })
    })
    req.on('error', function(e) {
      console.log("code换取token失败 : "+count+"  e: ")
      console.log(e)
      if(count > 3){
        cb(null,{"flag" : false,"err" : e})
        console.error(e);
      }else{
        module.exports.H5GetData(code,++count,cb)
      }
    })
}
//微信客户端登录换取openid
module.exports.access_token = function(code,appid,count,cb) {
  if(appidList[appid]){
    var myAppid = appid
    var MySecret = appidList[appid]
    var string = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+myAppid+"&secret="+MySecret+"&code="+code+"&grant_type=authorization_code"
    var req=https.get(string,function(res){
        var data = data
        res.on("data",function(chunk) {
          data += chunk
        })
        res.on("end",function() {
          data = data.replace("undefined","")
          data = JSON.parse(data)
          if(data.errcode || data.errmsg || !data.openid || !data.session_key){
            console.log(data)
            cb(data)
          }else{
            console.log("access_token",data)
            session_keyMap[data.openid] = {
              session_key : data.session_key,
              appid : myAppid
            }
            cb(data)
          }
        })
    })
    req.on('error', function(e) {
      console.log("access_token code换取token失败 : "+count+"  e: ")
      console.log(e)
      if(count > 3){
        cb(e)
        console.error(e);
      }else{
        module.exports.access_token(code,appid,++count,cb)
      }
    })
  }else{
    cb("appid error : "+appid)
  }
}

//微信小游戏使用临时登录凭证code 获取 session_key 和 openid
module.exports.code2accessToken = function(code,count,cb) {
    var string = "https://api.weixin.qq.com/sns/jscode2session?appid="+appid+"&secret="+appidList[appid]+"&js_code="+code+"&grant_type=authorization_code"
    var req=https.get(string,function(res){
        var data = data
        res.on("data",function(chunk) {
          data += chunk
        })
        res.on("end",function() {
          data = data.replace("undefined","")
          data = JSON.parse(data)
          if(data.errcode || data.errmsg || !data.openid || !data.session_key){
            console.log(data)
            cb(data)
          }else{
            console.log("code2accessToken",data)
            session_keyMap[data.openid] = {
              session_key : data.session_key,
              appid : appid
            }
            cb(data)
          }
        })
    })
    req.on('error', function(e) {
      console.log("code2accessToken code换取token失败 : "+count+"  e: ")
      console.log(e)
      if(count > 3){
        cb(e)
        console.error(e);
      }else{
        module.exports.code2accessToken(code,++count,cb)
      }
    })
}
//微信小游戏使用临时登录凭证code 带appid 获取 session_key 和 openid
module.exports.code2accessTokenWithAppid = function(code,appid,count,cb) {
  if(appidList[appid]){
    var myAppid = appid
    var MySecret = appidList[appid]
    var string = "https://api.weixin.qq.com/sns/jscode2session?appid="+myAppid+"&secret="+MySecret+"&js_code="+code+"&grant_type=authorization_code"
    var req=https.get(string,function(res){
        var data = data
        res.on("data",function(chunk) {
          data += chunk
        })
        res.on("end",function() {
          data = data.replace("undefined","")
          data = JSON.parse(data)
          if(data.errcode || data.errmsg || !data.openid || !data.session_key){
            console.log(data)
            cb(data)
          }else{
            console.log("code2accessTokenWithAppid",data)
            session_keyMap[data.openid] = {
              session_key : data.session_key,
              appid : myAppid
            }
            cb(data)
          }
        })
    })
    req.on('error', function(e) {
      console.log("code2accessTokenWithAppid code换取token失败 : "+count+"  e: ")
      console.log(e)
      if(count > 3){
        cb(e)
        console.error(e);
      }else{
        module.exports.code2accessTokenWithAppid(code,appid,++count,cb)
      }
    })
  }else{
    cb("appid error : "+appid)
  }
}
//微信小游戏登陆
module.exports.wxLogin = function(openid,session_key,encryptedData,iv) {
  if(session_keyMap[openid] && session_keyMap[openid].session_key === session_key){
    var myAppid = session_keyMap[openid].appid
    var pc = new WXBizDataCrypt(myAppid, session_key)
    var data = pc.decryptData(encryptedData,iv)
    if(!data || ! data.unionId){
      return openid
    }
    return data.unionId
  }else{
    return false
  }
}
//微信APP登录
module.exports.wxClientLogin = function(openid,token,cb) {
  var url = "https://api.weixin.qq.com/sns/userinfo?access_token="+token+"&openid="+openid
  //console.log(url)
  https.get(url,function(req,res){
    req.on('data',function(data){
      if(data.errcode){
        console.log("errcode : "+data.errcode)
        console.log("errmsg : "+data.errmsg)
        cb(false)
      }else{
        var result = JSON.parse(data)
        if(!result.unionid){
          result.unionid = result.openid
        }
        cb(result)
      }
    })
  })
}
module.exports.getTicket = function(cb) {
  //jsapi_ticket存在直接返回，不存在则开启获取
  if(jsapi_ticket){
    cb(null,{flag : true,"jsapi_ticket" : jsapi_ticket})
  }else{
    local.getAccess_token(cb)
    clearInterval(timer)
    timer = setInterval(local.getAccess_token,3600 * 1000)
  }
}
local.getAccess_token = function(cb) {
    var string = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appid+"&secret="+appidList[appid]
    var req=https.get(string,function(res){
        var data = data
        res.on("data",function(chunk) {
          data += chunk
        })
        res.on("end",function() {
          data = data.replace("undefined","")
          data = JSON.parse(data)
          if(data.errcode || !data.access_token){
            errorLogger.info("获取微信token失败!")
            errorLogger.info(data.errmsg)
            access_token = ""
            if(cb){
              cb(null,{flag : false})
            }
            return
          }
          access_token = data.access_token
          local.getJsapi_ticket(access_token,cb)
        })
    })
}
local.getJsapi_ticket = function(token,cb){
    var string = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+token+"&type=jsapi"
    var req=https.get(string,function(res){
        var data = data
        res.on("data",function(chunk) {
          data += chunk
        })
        res.on("end",function() {
          data = data.replace("undefined","")
          data = JSON.parse(data)
          if(data.errmsg !== "ok" || !data.ticket){
            errorLogger.info("获取微信ticket失败!")
            errorLogger.info(data.errmsg)
            jsapi_ticket = ""
            if(cb){
              cb(null,{flag : false})
            }
            return
          }
          jsapi_ticket = data.ticket
          if(cb){
            cb(null,{flag : true,"jsapi_ticket" : jsapi_ticket})
          }
        })
    })
}
var getCity = function(ip,cb) {
    var string = "http://ip.taobao.com/service/getIpInfo.php?ip="+ip
    var req=http.get(string,function(res){
        var data = data
        res.on("data",function(chunk) {
          data += chunk
        })
        res.on("end",function() {
          data = data.replace("undefined","")
          data = JSON.parse(data)
          if(cb){
            cb(data)
          }
        })
    })
    req.on('error', function(e) {
      console.log("获取IP失败 : "+ip)
      cb({"area" : "","region" : "", "city" : ""})
      console.error(e);
    })
}